<?php

class Db
{
	static $_instance = null;
    static $_pdo = null;

    CONST ESCAPE_FIELD = 1;
    CONST ESCAPE_VALUE = 2;

    static $_setting = array('host'=> 'P2DC-PC', 'user'=> 'root', 'password'=> '123456', 'dbname'=> 'p2dc', 'charset'=> 'utf8');
    //static $_setting = array('host'=> 'localhost', 'user'=> 'admin_p2dc', 'password'=> 'yrxK3jdD', 'dbname'=> 'admin_p2dc');
	
	private function __construct(){}
	
	static public function getInstance()
	{
		if(self::$_instance===null){
			self::$_instance = new mysqli(self::$_setting['host'], self::$_setting['user'], self::$_setting['password'], self::$_setting['dbname']);
			//self::$_instance->set_charset(self::$_setting['charset']);

			if(self::$_instance->errno){
				throw new Exception("Database connection failed: ".self::$_instance->error);
			}
		}
		return self::$_instance;
	}

    static public function getPDO()
    {
        if(self::$_pdo===null)
        {
            try {
                //self::$_pdo = new PDO("mysql:host=".self::$_setting['host'].";dbname=".self::$_setting['dbname'].";charset=".self::$_setting['charset'],
                self::$_pdo = new PDO("mysql:host=".self::$_setting['host'].";dbname=".self::$_setting['dbname'],
                    self::$_setting['user'],
                    self::$_setting['password']);

                self::$_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                //self::$_pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            }catch(PDOException $ex){
                self::$_pdo = null;
                exit();
            }
        }
        return self::$_pdo;
    }
	
	static public function real_escap_array($array)
	{
		if(gettype($array) != 'array'){
			throw new Exception('real_escap_array need array');
		}
		$buffer = array();
		foreach($array as $key => $value){
			$buffer[$key] = self::getInstance()->real_escape_string($value);
		}
		return $buffer;
	}
	
	static public function real_escap_implode($array)
	{
		$buffer = array();
		foreach($array as $key => $value){
			if(is_null($value)) $buffer[$key] = 'NULL';
			else $buffer[$key] = "'".self::getInstance()->real_escape_string($value)."'";
		}
		return implode(',', $buffer);
	}

    static public function escape($str, $option = null)
    {
        $option = is_null($option)? self::ESCAPE_FIELD: $option;
        if($option==self::ESCAPE_FIELD){
            //return $str;
        }
        return $str;
    }
}